
package com.scs.application.modules.upms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.modules.upms.entity.WxmpAccount;
import com.scs.application.modules.upms.request.WxmpAccountQueryRequest;
import com.scs.application.modules.upms.security.integration.authenticator.WxmpAuthenticator;
import com.scs.application.modules.upms.service.WxmpAccountService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 服务号 controller
 *
 */
@AllArgsConstructor
@RestController
@RequestMapping("/upms/wxmp_accounts")
public class WxmpAccountController extends CrudController<WxmpAccount, String, WxmpAccountService> implements ImAndExAbleController<WxmpAccountQueryRequest> {


    @GetMapping("/page")
    public PageResult page(WxmpAccountQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(WxmpAccountQueryRequest request) {
        List<WxmpAccount> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }


    /**
     * 同步到缓存
     *
     * @return
     */
    @Autowired
    private WxMpService wxMpService;

    @PostMapping("sync_to_cache")
    public CommonResult syncToCache() {
        Map<String, WxMpConfigStorage> configs = service.getAllWxMpConfig();
        wxMpService.setMultiConfigStorages(configs);


        //for (Map.Entry<String, WxMpConfigStorage> entry : configs.entrySet()) {
        //    CacheUtils.remove(WxmpAuthenticator.OAUTH_TYPE, entry.getKey());
        //}
        CacheUtils.clearCache(WxmpAuthenticator.OAUTH_TYPE);
        return CommonResult.ok("同步成功");
    }


}
